package cn.cqone.crm.service.impl;

import cn.cqone.crm.domain.Employee;
import cn.cqone.crm.domain.Role;
import cn.cqone.crm.domain.Tenant;
import cn.cqone.crm.mapper.EmployeeMapper;
import cn.cqone.crm.mapper.RoleMapper;
import cn.cqone.crm.mapper.TenantMapper;
import cn.cqone.crm.query.EmployeeQuery;
import cn.cqone.crm.service.EmployeeService;
import cn.cqone.crm.utils.PageList;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl extends BaseServiceImpl<Employee,Long, EmployeeQuery> implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private TenantMapper tenantMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Override
    public int add(Employee obj) {
        Employee employee =(Employee) SecurityUtils.getSubject().getPrincipal();
        Long tenantId = employeeMapper.findTenantId(employee.getUsername());
        Tenant byId = tenantMapper.findById(tenantId);
        obj.setTenant(byId);
        employee.setType(1);
        obj.setInputTime(new Date());
        if(employeeMapper.findByName(obj.getUsername())==null){
            obj.setPassword(new Md5Hash(obj.getPassword(), "wlt",7).toString());
            return super.add(obj);
        }
        else {
            return 0;
        }
    }

    @Override
    public Employee findByName(String name) {
        return employeeMapper.findByName(name);
    }

    //根据用户id和角色id分配角色
    @Override
    public void updateEmployeeRoleById(Long employeeId, Long roleId) {
        employeeMapper.updateEmployeeRoleById(employeeId,roleId);
    }

    @Override
    public PageList<Employee> findByPage(EmployeeQuery query) {
        Integer total = employeeMapper.findCount(query);
        if(total==0){
            return new PageList<>();
        }
        List<Employee> list = employeeMapper.findList(query);
        list.forEach(l->{
            Role role = roleMapper.findById(l.getRole_id());
            l.setRole(role);
        });
        return new PageList<>(total,list);
    }
}
